package com.kerbores.kop.servlet;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.nutz.json.Json;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;

import com.kerbores.kop.common.SignUtil;
import com.kerbores.utils.entries.Result;


/**
 * KOP框架入口
 * 
 * @author Kerbores
 *
 */
public class KOPServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	/**
	 * 默认的service调用入口
	 */
	public static String SERVICE_INVOKE_URL = "service";
	private static String CHARACTERENCODING;

	private boolean checkSign(HttpServletRequest request, String appKey, String appSecret, boolean fileUpload) {
		String sign = request.getHeader("sign");
		NutMap map = NutMap.NEW();
		Enumeration<String> enumeration = request.getParameterNames();
		while (enumeration.hasMoreElements()) {
			String key = (String) enumeration.nextElement();
			map.put(key, request.getParameter(key));
		}
		return Strings.equals(SignUtil.getSign(map, fileUpload, appKey, appSecret), sign);
	}

	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		CHARACTERENCODING = config.getInitParameter("charset");
		if (CHARACTERENCODING == null) {
			CHARACTERENCODING = "UTF-8";//默认编码 UTF-8
		}
		String serviceUrl = config.getInitParameter("service");
		if (!Strings.isBlank(serviceUrl)) {
			SERVICE_INVOKE_URL = serviceUrl;
		}
		if (!SERVICE_INVOKE_URL.startsWith("/")) {
			SERVICE_INVOKE_URL = "/" + SERVICE_INVOKE_URL;
		}
	}

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 编码
		request.setCharacterEncoding(CHARACTERENCODING);
		response.setCharacterEncoding(CHARACTERENCODING);
		// 检查签名
		boolean fileUpload = Strings.equals("1", request.getHeader("fileUpload"));
		String appKey = request.getHeader("appKey");
		String appSecret = request.getHeader("appSecret");

		if (!checkSign(request, appKey, appSecret, fileUpload)) {
			response.getWriter().write(Json.toJson(Result.exception("非法调用:签名不合法")));
			return;
		}

		// 获取request中的method参数作为调用url
		String method = request.getHeader("method");
		if (Strings.isBlank(method)) {
			response.getWriter().write(Json.toJson(Result.exception("调用method不能为空")));
			return;
		}
		// forward到指定地址
		request.getRequestDispatcher(SERVICE_INVOKE_URL + "/" + method).forward(request, response);
	}

}
